package com.gitee.fastmybatis.spring.boot.autoconfigure.multi;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Configuration
@ConfigurationProperties(prefix = "spring")
public class MultiDataSourceProps {
    public static final String SPRING_MULTI_DATASOURCE = "spring.multi-datasource";


    /**
     * 多数据源配置,key:配置名称,value配置项
     */
    private Map<String, DataSourceProp> multiDatasource;

    public Map<String, DataSourceProp> getMultiDatasource() {
        return multiDatasource;
    }

    public DatasourcePropContext getMainDataSourceProp() {
        Set<Map.Entry<String, DataSourceProp>> entrySet = multiDatasource.entrySet();
        if (entrySet.size() == 1) {
            Map.Entry<String, DataSourceProp> entry = entrySet.iterator().next();
            return DatasourcePropContext.ofMain(entry);
        }
        return entrySet.stream()
                .filter(entry -> entry.getValue().getMain())
                .findFirst()
                .map(DatasourcePropContext::ofMain)
                .orElseGet(() -> DatasourcePropContext.ofMain(entrySet.iterator().next()));
    }

    public List<DatasourcePropContext> getNotMainDataSourceProp() {
        if (multiDatasource.size() == 1) {
            return Collections.emptyList();
        }
        Map<String, DataSourceProp> retMap = new LinkedHashMap<>(multiDatasource);
        DatasourcePropContext mainDataSourceProp = getMainDataSourceProp();
        return retMap.entrySet()
                .stream()
                // 排除主数据源
                .filter(entry -> !Objects.equals(mainDataSourceProp.getDsAlias(), entry.getKey()))
                .map(DatasourcePropContext::ofNotMain)
                .collect(Collectors.toList());
    }

    public void setMultiDatasource(Map<String, DataSourceProp> multiDatasource) {
        this.multiDatasource = multiDatasource;
    }

}
